//
//  MPBTools+FilePath.m
//  MiaoPai
//
//  Created by jiaxuzhou on 2017/6/26.
//  Copyright © 2017年 Jeakin. All rights reserved.
//


#import "MPBTools+FilePath.h"


@implementation MPBTools (FilePath)


+ (MPBFilePath *)getGlobalFilePathManager
{
    return MPT_FilePathManager;
}

+ (NSString *)homeDirectory
{
    return MPT_FilePathManager.homePath;
}

+ (NSString *)tempDirectory
{
    return MPT_FilePathManager.tmpPath;
}

+ (NSString *)documentsDirectory
{
    return MPT_FilePathManager.docmentsPath;
}

+ (NSString *)libraryDirectory
{
    return MPT_FilePathManager.libraryPath;
}

+ (NSString *)cachesDirectory
{
    return MPT_FilePathManager.cachesPath;
}

+ (BOOL)createDirPath:(NSString *)path error:(NSError *__autoreleasing *)error
{
    BOOL success = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ( ![fileManager fileExistsAtPath:path] )
    {
        success = [fileManager createDirectoryAtPath:path
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:error];
    }
    
    return success;
}

+ (NSString *)createFileInCachePathWithSubPath:(NSString *)subPath
                                      fileName:(NSString *)fileName
                                        ofType:(NSString *)type
{
    NSString *dirPath = [MPT_FilePathManager.cachesPath stringByAppendingPathComponent:subPath];
    [self createDirPath:dirPath error:nil];
    
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",dirPath,fileName];

    if (type)
    {
        filePath = [NSString stringWithFormat:@"%@.%@",filePath,type];
    }
    
    return filePath;
}


#pragma mark - 删除文件(夹)

+ (BOOL)removeItemAtPath:(NSString *)path
{
    return [self removeItemAtPath:path error:nil];
}

+ (BOOL)removeItemAtPath:(NSString *)path
                   error:(NSError *__autoreleasing *)error
{
    return [[NSFileManager defaultManager] removeItemAtPath:path error:error];
}

+ (void)clearFilesDirectory:(MPE_FilesDirectory)filesDirectory
           CompletionHandle:(void(^)(BOOL finshed ))CompletionHandle
{
    NSArray *subFiles = [self listFilesInSearchPathDirectory:filesDirectory Deep:NO];
    BOOL isSuccess = YES;
    
    for (NSString *file in subFiles) {
        NSString *absolutePath = [[self cachesDirectory] stringByAppendingPathComponent:file];
        isSuccess &= [self removeItemAtPath:absolutePath];
    }
    
    CompletionHandle(isSuccess);
}


#pragma mark - 复制文件(夹)

+(void)copyItemAtPath:(NSString *_Nullable)path
               ToPath:(NSString *_Nullable)toPath
                Cover:(BOOL)cover
     CompletionHandle:(void(^_Nonnull)(BOOL finshed,NSError * _Nullable error))completionHandle
{
    /*
     1.检查源文件是否存在
     2.创建复制路径文件(夹)
     3。判断是否重写
     4.复制文件
     */
    NSError * error;
    if (![self isExistsAtPath:path])
    {
        completionHandle(NO,error);
    }
    
    NSString *toDirPath = [self directoryAtPath:toPath];
    if (![self isExistsAtPath:toDirPath])
    {
        if (![self createDirPath:toDirPath error:&error])
        {
            completionHandle(NO,error);
        }
    }
    
    if (cover)
    {
        if ([self isExistsAtPath:toPath])
        {
            [self removeItemAtPath:toPath error:&error];
        }
    }
    
    BOOL isSuccess = [[NSFileManager defaultManager] copyItemAtPath:path toPath:toPath error:&error];
    if (!isSuccess)
    {
        completionHandle(NO,error);
    }
    
    completionHandle(YES,error);
}

+ (void)copyItemAtFilePath:(NSString *_Nullable)path
                ToFilePath:(NSString *_Nullable)toPath
                     Cover:(BOOL)cover
          CompletionHandle:(void(^_Nonnull)(BOOL finshed,NSError * _Nullable error))completionHandle
{
    NSError * error;
    if (![self isExistsAtPath:path])
    {
        completionHandle(NO,error);
    }
    
    NSString *toDirPath = [self directoryAtPath:toPath];
    if (cover)
    {
        [self removeItemAtPath:toDirPath];
    }
    
    if (![self isExistsAtPath:toDirPath])
    {
        if (![self createDirPath:toDirPath error:&error])
        {
            completionHandle(NO,error);
        }
    }
    
    if ([self isExistsAtPath:toPath])
    {
        [self removeItemAtPath:toPath error:&error];
    }
    
    BOOL isSuccess = [[NSFileManager defaultManager] copyItemAtPath:path toPath:toPath error:&error];
    if (!isSuccess)
    {
        completionHandle(NO,error);
    }
    
    completionHandle(YES,error);
}


#pragma mark - 根据URL获取文件名

/**
 获取文件名

 @param path 文件路径
 @param suffix 是否展示扩展名
 @return 文件名
 */
+ (NSString *)fileNameAtPath:(NSString *)path suffix:(BOOL)suffix
{
    NSString *fileName = [path lastPathComponent];
    if (!suffix)
    {
        fileName = [fileName stringByDeletingPathExtension];
    }
    
    return fileName;
}

/**
 获取文件路径的上一级路径

 @param path 文件路径
 @return 文件路径的上一级路径
 */
+ (NSString *)directoryAtPath:(NSString *)path
{
    return [path stringByDeletingLastPathComponent];
}

/**
 获取文件路径的文件扩展名

 @param path 文件路径
 @return 文件路径的扩展名
 */
+ (NSString *)suffixAtPath:(NSString *)path
{
    return [path pathExtension];
}


#pragma mark - 遍历文件夹

+ (nullable NSArray * )listFilesInDirectoryAtPath:(nullable NSString *)path Deep:(BOOL)deep
{
    NSArray *listArr;
    NSError *error;
    NSFileManager *manager = [NSFileManager defaultManager];
    if (deep)
    {
        // 深遍历
        NSArray *deepArr = [manager subpathsOfDirectoryAtPath:path error:&error];
        if (!error)
        {
            listArr = deepArr;
        }
        else
        {
            listArr = nil;
        }
    }
    else
    {
        // 浅遍历
        NSArray *shallowArr = [manager contentsOfDirectoryAtPath:path error:&error];
        if (!error)
        {
            listArr = shallowArr;
        }
        else
        {
            listArr = nil;
        }
    }
    
    return listArr;
}

+ (nullable NSArray *)listFilesInSearchPathDirectory:(MPE_FilesDirectory)filesDirectory
                                                Deep:(BOOL)deep
{
    switch (filesDirectory)
    {
        case MPE_HomeDirectory:
            return [self listFilesInDirectoryAtPath:[self homeDirectory] Deep:deep];
            break;
        case MPE_TemporaryDirectory:
            return [self listFilesInDirectoryAtPath:[self tempDirectory] Deep:deep];
            break;
        case MPE_LibraryDirectory:
            return [self listFilesInDirectoryAtPath:[self libraryDirectory] Deep:deep];
            break;
        case MPE_DocumentDirectory:
            return [self listFilesInDirectoryAtPath:[self documentsDirectory] Deep:deep];
            break;
        case MPE_CachesDirectory:
            return [self listFilesInDirectoryAtPath:[self cachesDirectory] Deep:deep];
            break;
            
        default:
            
            return nil;
            break;
    }
    
    return nil;
}


#pragma mark - 获取文件属性

+ (NSDictionary *)attributesOfItemAtPath:(NSString *)path
{
    return [self attributesOfItemAtPath:path error:nil];
}

+ (id)attributeOfItemAtPath:(NSString *)path forKey:(NSString *)key
{
    return [[self attributesOfItemAtPath:path] objectForKey:key];
}

+ (id)attributeOfItemAtPath:(NSString *)path forKey:(NSString *)key error:(NSError *__autoreleasing *)error
{
    return [[self attributesOfItemAtPath:path error:error] objectForKey:key];
}

+ (NSDictionary *)attributesOfItemAtPath:(NSString *)path error:(NSError *__autoreleasing *)error
{
    return [[NSFileManager defaultManager] attributesOfItemAtPath:path error:error];
}


#pragma mark - 判断文件(夹)是否存在

+ (BOOL)isExistsAtPath:(NSString *)path
{
    return [[NSFileManager defaultManager] fileExistsAtPath:path];
}

+ (BOOL)isEmptyItemAtPath:(NSString *)path
{
    return [self isEmptyItemAtPath:path error:nil];
}

+ (BOOL)isEmptyItemAtPath:(NSString *)path error:(NSError *__autoreleasing *)error
{
    return ([self isFileAtPath:path error:error] &&
            [[self sizeOfItemAtPath:path error:error] intValue] == 0) ||
    ([self isDirectoryAtPath:path error:error] &&
     [[self listFilesInDirectoryAtPath:path Deep:NO] count] == 0);
}

+ (BOOL)isDirectoryAtPath:(NSString *)path
{
    return [self isDirectoryAtPath:path error:nil];
}

+ (BOOL)isDirectoryAtPath:(NSString *)path error:(NSError *__autoreleasing *)error
{
    return ([self attributeOfItemAtPath:path forKey:NSFileType error:error] == NSFileTypeDirectory);
}

+ (BOOL)isFileAtPath:(NSString *)path
{
    return [self isFileAtPath:path error:nil];
}

+ (BOOL)isFileAtPath:(NSString *)path error:(NSError *__autoreleasing *)error
{
    return ([self attributeOfItemAtPath:path forKey:NSFileType error:error] == NSFileTypeRegular);
}

+ (BOOL)isExecutableItemAtPath:(NSString *)path
{
    return [[NSFileManager defaultManager] isExecutableFileAtPath:path];
}

+ (BOOL)isReadableItemAtPath:(NSString *)path
{
    return [[NSFileManager defaultManager] isReadableFileAtPath:path];
}

+ (BOOL)isWritableItemAtPath:(NSString *)path
{
    return [[NSFileManager defaultManager] isWritableFileAtPath:path];
}


#pragma mark - 获取文件(夹)大小

+ (NSNumber *)sizeOfItemAtPath:(NSString *)path
{
    return [self sizeOfItemAtPath:path error:nil];
}

+ (NSNumber *)sizeOfItemAtPath:(NSString *)path error:(NSError *__autoreleasing *)error
{
    return (NSNumber *)[self attributeOfItemAtPath:path forKey:NSFileSize error:error];
}

+ (NSNumber *)sizeOfFileAtPath:(NSString *)path
{
    return [self sizeOfFileAtPath:path error:nil];
}

+ (NSNumber *)sizeOfFileAtPath:(NSString *)path error:(NSError *__autoreleasing *)error
{
    if ([self isFileAtPath:path error:error])
    {
        return [self sizeOfItemAtPath:path error:error];
    }
    return nil;
}

+ (NSNumber *)sizeOfDirectoryAtPath:(NSString *)path
{
    return [self sizeOfDirectoryAtPath:path error:nil];
}

+ (NSNumber *)sizeOfDirectoryAtPath:(NSString *)path error:(NSError *__autoreleasing *)error
{
    if ([self isDirectoryAtPath:path error:error])
    {
        NSArray *subPaths = [self listFilesInDirectoryAtPath:path Deep:YES];
        NSEnumerator *contentsEnumurator = [subPaths objectEnumerator];
        
        NSString *file;
        unsigned long long int folderSize = 0;
        
        while (file = [contentsEnumurator nextObject])
        {
            NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[path stringByAppendingPathComponent:file] error:nil];
            folderSize += [[fileAttributes objectForKey:NSFileSize] intValue];
        }
        
        return [NSNumber numberWithUnsignedLongLong:folderSize];
    }
    
    return nil;
}

+ (NSString *)clearCache
{
    //清除缓存目录
    NSString *cachesPath = [self cachesDirectory];
    
    NSString *str = [NSString stringWithFormat:@"缓存已清除%.1fM", [[self sizeOfDirectoryAtPath:cachesPath] integerValue]/1024.0/1024.0];

    NSLog(@"%@",str);
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachesPath];
    for (NSString *p in files)
    {
        NSError *error;
        NSString *currPath = [cachesPath stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:currPath])
        {
            BOOL ret = [[NSFileManager defaultManager] removeItemAtPath:currPath error:&error];
            NSLog(@"移除文件 %@ ret= %d", currPath, ret);
        }
        else
        {
            NSLog(@"文件不存在 %@", currPath);
        }
    }
    
    return str;
}


@end


@implementation NSString (FilePath)


- (NSString * (^)(NSString *))subFileName
{
    return ^NSString *(NSString *subFileName)
    {
        return [self stringByAppendingPathComponent:subFileName];
        
    };
}

- (NSString * (^)(NSString *))subPathName
{
    return ^NSString *(NSString *subPathName)
    {
        NSString *path = [self stringByAppendingPathComponent:subPathName];
        
        [MPBTools createDirPath:path error:nil];
        
        return path;
    };
}


@end
